<template>
	<view class="post" :class="[isDark?'dark':'', AppStyle]" :style="{'background-color':isDark?'#1c1c1c':'#f6f6f6','max-height':isDark?'100vh':'auto'}">
		<view class="header" :style="[{height:CustomBar + 'px'}]" v-if="showContent">
			<view class="cu-bar" :class="isDark?'dark':'bg-white'" :style="{'height': CustomBar + 'px','padding-top':StatusBar + 'px','background-color':isDark?'#1c1c1c':'#ffffff'}">
				<view class="action" @tap="isback">
					<text class="cuIcon-back"></text>
				</view>
				<view class="content text-bold" :style="[{top:StatusBar + 'px'}]">
					<block v-if="type=='edit'">
						{{$t('global.editpost')}}
					</block>
					<block v-else>
						{{$t('global.publishpost')}}
					</block>
				</view>
				<!--  #ifdef H5 || APP-PLUS -->
				<view class="action" @click="toDraft()" style="display: flex;color: #333;">
					<block v-if="type=='add'">
						<text style="margin-right: 5px;">{{$t('global.drafts')}}</text>
						<span class="tn-icon-edit-form" style="font-size: 40upx;"></span>
					</block>
				</view>
				<!--  #endif -->
			</view>
		</view>
		<view :style="[{padding:(NavBar+10) + 'px 10px 0px 10px'}]"></view>
		<form>
			<view class="cu-form-group margin-sm bg-white" style="border-radius: 20upx;">
				<input placeholder="$t('edit.addpost.plsposttitle')" name="input" v-model="title" :adjust-position="false" :focus="false"/>
				<block v-if="type=='add'">
					<view class="picker" style="color: #333;" @tap="toCategory">
						<block v-if="sectionName==$t('global.unknowncircle')">
							{{$t('global.selectcircle')}}
						</block>
						<block v-else>
							<text class="text-shojo">{{sectionName}}</text>
						</block>
					</view>
				</block>
			</view>
			<view class="bg-white margin-sm" style="border-radius: 20upx;">
				<view class="margin-sm">
					<cu-editor ref="editor" :mrPoster="videoPoster" :SPimg="SPimg" :musicpic='musicpic' editorId='editor' :NavBar="NavBar" @editorFocus="handleEditorFocus" :uploadTime="uploadTime" @editorBlur="handleEditorBlur" :url="this.$API.upload()" :formData="formData" :content="text" :MusicUpload='MusicUpload' :isPay="false" :isWz="false" @save="onSave"></cu-editor>
				</view>
			</view>
			<view :style="showContent?'':'display:none'" class="bg-white margin-sm" style="border-radius: 20upx; padding: 14px;">
				<view class="flex flex-row justify-between items-center" style="align-items: center;">
					<text style="color: #333;">{{$t('edit.addpost.ispaycontext')}}</text>
					<tn-switch :disabled="isPayShop" v-model="isPaid" />
				</view>
				<view v-if="isPaid" class="margin-top-sm">
					<tn-button :backgroundColor="isDark?'#3c3c3c':'#f6f6f6'" fontColor='#444' width='100%' @click="editPaidContent">
						{{$t('edit.addpost.editpaycontext')}}
					</tn-button>
				</view>
			</view>
			<view :style="showContent?'':'display:none'">
				<!--#ifdef APP-PLUS || H5 -->
				<view v-if="type=='add'" class="margin-sm" style="display: flex;justify-content: space-between;">
					<tn-button type="button" fontColor="#333" :backgroundColor="isDark?'#2c2c2c':'#fff'" width="35%" class="form-btn" @click="submit(false)">
						{{$t('edit.addpost.savedrafts')}}
					</tn-button>
					<tn-button type="button" backgroundColor="rgb(1, 190, 255)" fontColor="#fff" width="60%" class="form-btn" @click="submit(true)">
						{{$t('global.publishpost')}}
					</tn-button>
				</view>
				<!--#endif -->
				<!--#ifdef MP-WEIXIN -->
				<view v-if="type=='add'" class="margin-sm">
					<tn-button type="button" fontColor="#333" :backgroundColor="isDark?'#2c2c2c':'#fff'" width="100%" class="form-btn" @click="submit(false)">
						{{$t('edit.addpost.savedrafts')}}
					</tn-button>
					<view class="margin-top-sm">
						<tn-button class="form-btn margin-top-sm" type="button" backgroundColor="rgb(1, 190, 255)" fontColor="#fff" width="100%" @click="submit(true)">
							{{$t('global.publishpost')}}
						</tn-button>
					</view>
				</view>
				<!--#endif -->
				<view v-else class="margin-sm">
					<tn-button type="button" backgroundColor="rgb(1, 190, 255)" fontColor="#fff" width="100%" class="form-btn" @click="submit(true)">
						<block v-if="draft==0">
							{{$t('global.editpost')}}
						</block>
						<block v-if="draft==1">
							{{$t('global.publishpost')}}
						</block>
					</tn-button>
				</view>
				<!--  #ifdef MP-WEIXIN -->
				<view class="margin-sm">
					<tn-button type="button" fontColor="#333" width="100%" class="form-btn" @click="toDraft()">
						<text style="margin-right: 5px;">{{$t('global.drafts')}}</text>
						<span class="tn-icon-edit-form" style="font-size: 30upx;"></span>
					</tn-button>
				</view>
				<!--  #endif -->
			</view>
		</form>
		<view class="dark-bg" style="height: 700rpx;background: #1c1c1c;" v-if="isDark"></view>
	</view>
</template>

<script>
	import mpHtml from '@/components/mp-html/mp-html'
	import {
		localStorage
	} from '../../js_sdk/mp-storage/mp-storage/index.js'
	import darkModeMixin from '@/utils/darkModeMixin.js'
	var wv;
	export default {
		mixins: [darkModeMixin],
		data() {
			return {
				StatusBar: this.StatusBar,
				CustomBar: this.CustomBar,
				NavBar: this.StatusBar + this.CustomBar,
				AppStyle: this.$store.state.AppStyle,
				isPaid: false,
				modalName: "",
				showContent: true,
				havePay: false,
				uid: 0,
				uploadTime: this.$API.getuploadTime(),
				token: "",
				poster: this.$API.SPmusicpic(),
				isShow: false,
				isPayShop: false,
				name: "",
				curHeight: 0,
				jpHeight: 0,
				screenHeight: 0,
				postheight: 0,
				poststyle: "",
				readstyle: "",
				isText: 0,
				draft: 0,
				MusicUpload: this.$API.SPstarMusicUpload(),
				musicpic: this.$API.SPmusicpic(),
				videoPoster: this.$API.getVideoPoster(),
				SPimg: this.$API.SPimgs(),
				formData: {},
				//文章表单部分
				title: "",
				category: "",
				list: [{
					value:"123",
					label: $t('edit.addpost.thisdefault'),
				}],
				tag: "",
				categoryText: "",
				text: '',
				textRead: "",
				isLoading: false,
				isSpace: false,
				//页面状态
				type: "add",
				id: 0,
				lenght: 0,
				payId: 0,
				shopList: [],
				editInterval: null,
				shopID: -1,
				sectionName: $t('global.unknowncircle'),
				sectionid: 0,
				content: "",
			}
		},
		onPullDownRefresh() {

		},
		onShow() {

		},
		onHide() {
			var that = this;
			clearInterval(that.editInterval);
			that.editInterval = null;
		},
		onShow() {
			var that = this;
			if (localStorage.getItem('userinfo')) {
				var userInfo = JSON.parse(localStorage.getItem('userinfo'));
				that.token = userInfo.token;
				if (userInfo.screenName) {
					that.name = userInfo.screenName;
				} else {
					that.name = userInfo.name;
				}
				that.formData = {
					'token': userInfo.token,
					'username': that.name
				}
			}
			if (localStorage.getItem('curSection')) {
				var curSection = JSON.parse(localStorage.getItem('curSection'));
				that.sectionid = curSection.id;
				that.sectionName = curSection.name;
				localStorage.removeItem('curSection');
			}
		},
		onLoad(res) {
			var that = this;
			localStorage.setItem('isSaveTz', "false");
			that.editInterval = setInterval(function() {
				if (localStorage.getItem('goBack')) {
					localStorage.removeItem('goBack');
					that.back();
				}
			}, 500);
			var cachedPlugins = localStorage.getItem('getPlugins');
			if (cachedPlugins) {
				const pluginList = JSON.parse(cachedPlugins);
				// 检查插件是否存在于插件列表中 
			}
			// #ifdef APP-PLUS || MP
			that.NavBar = that.CustomBar;
			// #endif
			if (res.type) {
				that.type = res.type;
			}
			if (res.draft) {
				that.draft = res.draft;
			}
			if (that.type != 'add') {
				if (!res.id) {
					uni.showToast({
						title: that.$t('edit.addpost.paranoempty'),
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					that.back();
					return false;
				} else {
					that.id = res.id;
				}
			}
			if (res.type) {
				that.type = res.type;
				if (res.id) {
					that.id = res.id;
					that.setloading();
					var timer = setTimeout(function() {
						that.postInfoForum(that.id);
					}, 500)
				}
			}
			if (res.section) {
				that.sectionName = res.section;
			}
			if (res.sectionid) {
				that.sectionid = res.sectionid;
			}
			var verifyLevel = 0;
			if (localStorage.getItem('AppInfo')) {
				try {
					var AppInfo = JSON.parse(localStorage.getItem('AppInfo'));
					verifyLevel = AppInfo.verifyLevel;
				} catch (e) {
					console.log(e);
				}
			}
			if (localStorage.getItem('userinfo')) {
				var userInfo = JSON.parse(localStorage.getItem('userinfo'));
				that.token = userInfo.token;
				that.uid = userInfo.uid;
				that.uid = userInfo.uid;
				if (userInfo.screenName) {
					that.name = userInfo.screenName;
				} else {
					that.name = userInfo.name;
				}
			}
		},
		methods: {
			changeTopic(){
				const that = this;
				that.show = true;
				that.getTopic();
			},
			
			confirm(e) {
				const that = this;
				that.changeText = e[0].label;
				that.value = e[0].value;
			},
			setloading() {
				var that = this;
				if (!that.isLoading) {
					uni.showLoading({
						title: that.$t('global.obtaindata'),
					});
				} else {
					uni.hideLoading();
				}
			},
			editPaidContent() {
				uni.navigateTo({
					url: '/pages/edit/payText?havePay=' + this.havePay + '&sid=' + this.payId
				});
			},
			postInfoForum(id) {
				var that = this;
				var token = "";
				if (localStorage.getItem('userinfo')) {
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token = userInfo.token;
				}
				var data = {
					"id": id,
					"token": token,
				}
				that.$Net.request({
					url: that.$API.postInfoForum(),
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if (res.data.code == 1) {
							that.title = res.data.data.title;
							var textOld = res.data.data.text;
							var textNew = textOld.replace(
								/<video[^>]*?src="([^"]+)"[^>]*?(poster="([^"]+)")?[^>]*?>\s*<\/video>/g,
								(match, src, posterAttr, poster) => {
									const finalPoster = poster ? poster : that.videoPoster;
									return `<img src="${finalPoster}" alt="src=${src}|poster=${finalPoster}|type=video" />`;
								}
							);
							that.text = textNew;
							var sid = res.data.data.sid;
							if (sid > 0) {
								that.getPaid(sid)
							}
							that.isLoading = true;
							that.setloading();
						}
					},
					fail: function(res) {}
				})
			},
			getShopList() {
				var that = this;
				var uid = 0;
				if (localStorage.getItem('userinfo')) {

					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					uid = userInfo.uid;

				} else {
					uni.showToast({
						title: that.$t('common.plslogin'),
						icon: 'none',
						duration: 1000,
					});
					var timer = setTimeout(function() {
						uni.navigateTo({
							url: '/pages/user/login'
						});
						clearTimeout('timer')
					}, 1000)
					return false
				}
				var data = {
					"uid": uid,
					"status": 1,
				}
			},
			getPaid(sid) {
				var that = this;
				var searchParams = {
					"id": sid,
					"status": 1,
					"type": 4,
				}
				that.$Net.request({
					url: that.$API.shopList(),
					data: {
						"searchParams": JSON.stringify(that.$API.removeObjectEmptyKey(searchParams)),
						"token": that.token
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if (res.data.code == 1) {
							var list = res.data.data;
							if (list.length > 0) {
								that.isPaid = true;
								var paidInfo = list[0];
								that.shopID = paidInfo.id;
								if (paidInfo.value) {
									var text = paidInfo.value;
									that.havePay = true
								}
								that.isPayShop = true;
								var shopPice = paidInfo.price;
								var shopDiscount = paidInfo.vipDiscount;
								var payData = {
									text: paidInfo.value || "",
									shopPice: paidInfo.price,
									shopDiscount: paidInfo.vipDiscount
								};
								localStorage.setItem("payId" + sid, JSON.stringify(payData));
								that.payId = sid
							}
						}
					},
					fail: function(res) {
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
					}
				})
			},
			back() {
				localStorage.removeItem('isSaveTz')
				uni.navigateBack({
					delta: 1
				});
			},
			toDraft() {
				uni.navigateTo({
					url: '/pages/forum/draftList'
				});
			},
			okBtn() {
				const nowDate = +new Date();
				uni.setStorageSync('modelView', nowDate);
				this.cancleBtn();
			},
			handleEditorFocus() {
				this.showContent = false;
				this.NavBar = this.StatusBar;
			},
			handleEditorBlur() {
				this.showContent = true;
				this.NavBar = that.CustomBar;
			},
			cancleBtn() {
				this.modelVisible = false;
			},
			toSpace(e) {
				this.isSpace = e.detail.value
			},
			submit(isPost) {
				var that = this;
				var type = that.type;
				if (isPost) {
					if (type == "add") {
						that.$refs.editor.save()
						setTimeout(function() {
							that.postForum(false);
						}, 200)
					} else {
						that.$refs.editor.save();
						setTimeout(function() {
							that.editForum();
						}, 200)
					}
				} else {
					if (type == "add") {
						that.$refs.editor.save()
						setTimeout(function() {
							that.postForum(true);
						}, 200)
					}
				}
				// if(that.shopID!=-1){
				// 	that.mountShop();
				// }
			},
			onSave(e) {
				var that = this
				that.content = e.html;
			},
			postForum(Draft) {
				var that = this;
				if (that.title == "") {
					uni.showToast({
						title: that.$t('global.titlenoempty'),
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					return false
				}
				if (that.content == '<p><br></p>' || that.content == '') {
					uni.showToast({
						title: that.$t('global.contextnoempty'),
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					return false
				}
				if (that.sectionid == 0) {
					uni.showToast({
						title: that.$t('global.plsselectcircle'),
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					return false
				}
				var text = that.content;
				text = text.replace(/\r\n/g, "||rn||");
				text = text.replace(/\n/g, "||rn||");
				var isDraft = 0;
				if (Draft) {
					isDraft = 1
				}
				var data = {
					'title': that.title,
					'text': text,
					'isMd': 0,
					"isDraft": isDraft,
					"section": that.sectionid,
					"token": that.token,
				}
				var isPay = 0;
				if (that.isPaid) {
					isPay = 1;
					data.isPaid = isPay;
					if (that.havePay && that.payId != '0') {
						var payData = JSON.parse(localStorage.getItem("payId" + that.payId));
						if (payData) {
							data.shopText = payData.text;
							data.shopPice = payData.shopPice;
							data.shopDiscount = payData.shopDiscount;
						}
					} else {
						var payData = JSON.parse(localStorage.getItem("payIdmy"));
						if (payData) {
							data.shopText = payData.text;
							data.shopPice = payData.shopPice;
							data.shopDiscount = payData.shopDiscount;
						}
					}
				}
				uni.showLoading({
					title: that.$t('common.loadmore')
				});
				that.$Net.request({
					url: that.$API.postForum(),
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "post",
					dataType: 'json',
					success: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						if (res.data.code == 1) {
							if (!Draft) {
								// 设置刷新标记
								localStorage.setItem('needRefreshHome', 'true');
								localStorage.setItem('needRefreshFind', 'true');
								localStorage.setItem('needRefreshPosts_' + that.sectionid, 'true');
								
								uni.showToast({
									title: res.data.msg,
									icon: 'none',
								})
								localStorage.removeItem('payIdmy');
								// 清除发帖标记
								localStorage.removeItem('isPosting_' + that.sectionid);
								
								// 发布成功后退后2页（返回到圈子选择页之前）
								var timer = setTimeout(function() {
									uni.navigateBack({
										delta: 2
									});
								}, 1000)
							} else {
								localStorage.setItem('isSaveTz', "true");
								uni.showToast({
									title: that.$t('edit.addpost.alsavedrafts'),
									icon: 'none',
								})
							}
						} else {
							uni.showToast({
								title: res.data.msg,
								mask: false,
								icon: 'icon-error',
								duration: 3000
							})
						}
					},
					fail: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
						uni.stopPullDownRefresh()
					}
				})
			},
			editForum() {
				var that = this;
				if (that.title == "") {
					uni.showToast({
						title: that.$t('global.titlenoempty'),
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					return false
				}
				if (that.content == '<p><br></p>' || that.content == '') {
					uni.showToast({
						title: that.$t('global.contextnoempty'),
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					return false
				}
				if (that.sectionid == 0) {
					uni.showToast({
						title: that.$t('global.plsselectcircle'),
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					return false
				}
				var text = that.content;

				text = text.replace(/\r\n/g, "||rn||");
				text = text.replace(/\n/g, "||rn||");
				var data = {
					'id': that.id,
					'title': that.title,
					'text': text,
					"token": that.token,
					'isMd': 0
				}
				var isPay = 0;
				if (that.isPaid) {
					isPay = 1;
					data.isPaid = isPay;
					if (that.havePay && that.payId != '0') {
						var payData = JSON.parse(localStorage.getItem("payId" + that.payId));
						if (payData) {
							data.shopText = payData.text;
							data.shopPice = payData.shopPice;
							data.shopDiscount = payData.shopDiscount;
						}
					} else {
						var payData = JSON.parse(localStorage.getItem("payIdmy"));
						if (payData) {
							data.shopText = payData.text;
							data.shopPice = payData.shopPice;
							data.shopDiscount = payData.shopDiscount;
						}
					}
				} else {
					data.isPaid = isPay;
				}
				uni.showLoading({
					title: that.$t('common.loadmore')
				});
				that.$Net.request({
					url: that.$API.editForum(),
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "post",
					dataType: 'json',
					success: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: res.data.msg,
							icon: 'none',
						})
						if (res.data.code == 1) {
							localStorage.setItem('isEdit', true);
							// 设置刷新标记，通知板块详情页需要刷新
							localStorage.setItem('needRefreshPosts_' + that.sectionid, 'true');
							var timer = setTimeout(function() {
								that.back();
							}, 1000)

						}
					},
					fail: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: res.data.msg,
							mask: false,
							icon: 'icon-error',
							duration: 3000
						})
						uni.stopPullDownRefresh()
					}
				})
			},
			toCategory() {
				uni.navigateTo({
					url: '/pages/forum/section?type=1'
				});
			},
			addTag() {
				uni.navigateTo({
					url: '/pages/contents/alltag?type=edit'
				});
			},
			toPostlinktype(i) {
				var that = this;
				that.postlinktype = i;
			},
			toAddShop() {
				uni.navigateTo({
					url: '/pages/edit/addshop'
				});
			},
			goImgData() {
				uni.navigateTo({
					url: '/pages/contents/imagetoday?type=post'
				});
			},
			isback() {
				var that = this;
				var isSave = localStorage.getItem('isSaveTz');
				if (isSave == 'true') {
					that.back()
				} else {
					uni.showModal({
						title: that.$t('global.prompt'),
						content: that.$t('global.editnosave'),
						cancelText: that.$t('global.exit'),
						confirmText: that.$t('global.leave'),
						success: function(res) {
							if (res.confirm) {

							} else if (res.cancel) {
								that.back()
							}
						}
					});
				}
			}
		}
	}
</script>

<style>
	.post {
		display: flex;
		flex: 1;
		flex-direction: column;
		justify-content: space-between;
	}
</style>